package tableview

import (
	"image"
	"image/color"

	"gioui.org/layout"
	"gioui.org/op"
	"gioui.org/unit"
	"gioui.org/widget"
	"gioui.org/widget/material"
	"gioui.org/x/component"
)

type TableView struct {
	Labels    []string
	Theme     *material.Theme
	GridState component.GridState
}

type TableRow struct {
	Datum []string
}

func (tv *TableView) Layout(gtx layout.Context, tableRows []TableRow) layout.Dimensions {
	minSize := gtx.Dp(unit.Dp(200))
	border := widget.Border{Color: color.NRGBA{A: 255}, Width: unit.Dp(1)}
	inset := layout.UniformInset(unit.Dp(2))

	// Configure a label styled to be a heading.
	headingLabel := material.Body1(tv.Theme, "")
	headingLabel.MaxLines = 1
	dataLabel := material.Body1(tv.Theme, "")
	dataLabel.MaxLines = 1

	orig := gtx.Constraints
	gtx.Constraints.Min = image.Point{}
	macro := op.Record(gtx.Ops)
	dims := inset.Layout(gtx, headingLabel.Layout)
	_ = macro.Stop()
	gtx.Constraints = orig

	return component.Table(tv.Theme, &tv.GridState).Layout(gtx, len(tableRows), len(tv.Labels),
		func(axis layout.Axis, index, constraint int) int {
			if axis == layout.Horizontal {
				return int(max(int(float32(constraint)/float32(len(tv.Labels))), minSize))
			} else {
				return dims.Size.Y
			}
		},
		func(gtx layout.Context, col int) layout.Dimensions {
			return border.Layout(gtx, func(gtx layout.Context) layout.Dimensions {
				return inset.Layout(gtx, func(gtx layout.Context) layout.Dimensions {
					headingLabel.Text = tv.Labels[col]
					return headingLabel.Layout(gtx)
				})
			})
		},
		func(gtx layout.Context, row, col int) layout.Dimensions {
			return inset.Layout(gtx, func(gtx layout.Context) layout.Dimensions {
				dataLabel.Text = tableRows[row].Datum[col]
				return dataLabel.Layout(gtx)
			})
		},
	)
}

func max(a, b int) int {
	if a > b {
		return a
	}
	return b
}
